package one.bugu.android.demon.util;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import one.bugu.android.demon.R;

/**
 * Description MyTextUtils 文本处理工具类
 *
 * @author liuxin
 * @date 2018/10/26 16:33
 */
public class MyTextUtils {

    /**
     * 单例对象
     */
    private static volatile MyTextUtils singleton = null;

    private MyTextUtils() {

    }

    /**
     * 获取单例对象
     *
     * @return 单例对象
     */
    public static MyTextUtils getInstance() {
        if (singleton == null) {
            synchronized (MyTextUtils.class) {
                if (singleton == null) {
                    singleton = new MyTextUtils();
                }
            }
        }
        return singleton;
    }

    /**
     * 设置文本字体大小
     *
     * @param content 文本内容
     * @param start   开始位置
     * @param end     结束位置
     * @return
     */
    public SpannableString setAutoTextSize(String content, int start, int end, int textSize) {
        SpannableString spanString = new SpannableString(content);
        AbsoluteSizeSpan span = new AbsoluteSizeSpan(textSize);
        spanString.setSpan(span, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return spanString;
    }

    /**
     * 按照正则表达式设置指定text颜色
     *
     * @param text
     * @param target    正则
     * @param textColor
     * @return
     */
    public SpannableString setAutoTextColor(String text, String target, String textColor) {
        SpannableString spannableString = new SpannableString(text);
        Pattern pattern = Pattern.compile(target);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor(textColor));
            spannableString.setSpan(colorSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
    /**
     * 按照正则表达式设置指定text颜色
     *
     * @param text
     * @param target    正则
     * @return
     */
    public SpannableString setAutoTextBackGroundColor(String text, String target, String bgColor, String fgColor) {
        SpannableString spannableString = new SpannableString(text);
        Pattern pattern = Pattern.compile(target);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            BackgroundColorSpan colorSpan = new BackgroundColorSpan(Color.parseColor(bgColor));
            spannableString.setSpan(colorSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ForegroundColorSpan fColorSpan = new ForegroundColorSpan(Color.parseColor(fgColor));
            spannableString.setSpan(fColorSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    /**
     * 按照正则表达式设置指定text颜色
     *
     * @param text
     * @param textColor
     * @return
     */
    public SpannableString setAutoTextColor(String text, int startIndex, int endIndex, String textColor) {
        SpannableString spannableString = new SpannableString(text);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor(textColor));
        spannableString.setSpan(colorSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /**
     * 设置TextView段落间距
     *
     * @param context          上下文
     * @param tv               给谁设置段距，就传谁
     * @param content          文字内容
     * @param paragraphSpacing 请输入段落间距（单位dp）
     * @param lineSpacingExtra xml中设置的的行距（单位dp）
     */
    public void setParagraphSpacing(Context context, TextView tv, String content, int paragraphSpacing, int lineSpacingExtra) {
        if (!content.contains("\n")) {
            tv.setText(content);
            return;
        }
        content = content.replace("\n", "\n\r");

        int previousIndex = content.indexOf("\n\r");
        //记录每个段落开始的index，第一段没有，从第二段开始
        List<Integer> nextParagraphBeginIndexes = new ArrayList<>();
        nextParagraphBeginIndexes.add(previousIndex);
        while (previousIndex != -1) {
            int nextIndex = content.indexOf("\n\r", previousIndex + 2);
            previousIndex = nextIndex;
            if (previousIndex != -1) {
                nextParagraphBeginIndexes.add(previousIndex);
            }
        }
        //获取行高（包含文字高度和行距）
        float lineHeight = tv.getLineHeight();

        //把\r替换成透明长方形（宽:1px，高：字高+段距）
        SpannableString spanString = new SpannableString(content);
        Drawable d = ContextCompat.getDrawable(context, R.drawable.paragraph_space);
        float density = context.getResources().getDisplayMetrics().density;
        //int强转部分为：行高 - 行距 + 段距
        d.setBounds(0, 0, 1, (int) ((lineHeight - lineSpacingExtra * density) / 1.2 + (paragraphSpacing - lineSpacingExtra) * density));

        for (int index : nextParagraphBeginIndexes) {
            // \r在String中占一个index
            spanString.setSpan(new ImageSpan(d), index + 1, index + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        tv.setText(spanString);
    }
}
